package com.weepal.pavement.mqtt.demo.analysis.dataSender;

import com.weepal.pavement.mqtt.demo.vo.MqttDevices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class RedisSender {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * @param deviceKid 设备id
     * @param key       设备对应jsonkey
     * @param data      jsonkey下的值
     */
    public void send(MqttDevices devices, String field, String key, LinkedList<String> data) {
        try {
            redisTemplate.opsForHash().put(devices.getKid(), devices.getRedisKey(), array2map(field, data));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private ConcurrentHashMap<String, String> array2map(String field, LinkedList<String> data) {
        String[] split = field.split(",");
        int size = split.length;
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>(8);
        for (int i = 0; i < size; i++) {
            String val = data.removeFirst();
            String key = split[i];
            map.put(key, val);
        }
        return map;
    }
}
